/**
 * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef ECMASCRIPT_MEM_C_STRING_H
#define ECMASCRIPT_MEM_C_STRING_H

#include <sstream>
#include <string>
#include <string_view>

#include "plugins/ecmascript/runtime/common.h"
#include "runtime/include/mem/panda_string.h"

namespace ark::ecmascript {
class EcmaString;

// PRINT will skip '\0' in utf16 during conversion of utf8
enum StringConvertedUsage { PRINT, LOGICOPERATION };

PandaString ConvertToPandaString(const ecmascript::EcmaString *s,
                                 StringConvertedUsage usage = StringConvertedUsage::PRINT);
PandaString ConvertToPandaString(const ecmascript::EcmaString *s, uint32_t start, uint32_t length,
                                 StringConvertedUsage usage = StringConvertedUsage::PRINT);

template <class T>
std::enable_if_t<std::is_integral_v<T>, PandaString> ToPandaString(T number)
{
    if (number == 0) {
        return PandaString("0");
    }
    bool isNeg = false;
    if (number < 0) {
        number = -number;
        isNeg = true;
    }

    static constexpr uint32_t BUFF_SIZE = std::numeric_limits<T>::digits10 + 3;  // 3: Reserved for sign bit and '\0'.
    std::array<char, BUFF_SIZE> buf {};
    uint32_t position = BUFF_SIZE - 1;
    buf[position] = '\0';
    while (number > 0) {
        // NOLINTNEXTLINE(readability-magic-numbers)
        buf[--position] = number % 10 + '0';  // 10 : decimal
        // NOLINTNEXTLINE(readability-magic-numbers)
        number /= 10;  // 10 : decimal
    }
    if (isNeg) {
        buf[--position] = '-';
    }
    return PandaString(&buf[position]);
}
}  // namespace ark::ecmascript

#endif  // ECMASCRIPT_MEM_C_STRING_H
